import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Space,
  Typography,
  Row,
  Col,
  Statistic,
  Tag,
  Popconfirm,
  message,
  Empty
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  EyeOutlined,
  CalculatorOutlined
} from '@ant-design/icons';
import { stockPlanService, SavedStockPlan } from '../../../services/stockPlanService';
import { ColumnsType } from 'antd/es/table';

const { Title, Text } = Typography;

export type SavedStockInvestmentPlan = SavedStockPlan;

interface StockInvestmentPlanListProps {
  onCreateNew: () => void;
  onEdit: (plan: SavedStockInvestmentPlan) => void;
  onView: (plan: SavedStockInvestmentPlan) => void;
  onDelete: (id: string) => void;
}

const StockInvestmentPlanList: React.FC<StockInvestmentPlanListProps> = ({
  onCreateNew,
  onEdit,
  onView,
  onDelete
}) => {
  const [plans, setPlans] = useState<SavedStockInvestmentPlan[]>([]);
  const [loading, setLoading] = useState<boolean>(false);

  useEffect(() => {
    loadPlans();
  }, []);

  const loadPlans = async () => {
    try {
      setLoading(true);
      const savedPlans = await stockPlanService.getStockPlans();
      setPlans(savedPlans);
    } catch (error) {
      console.error('加载投资计划失败:', error);
      message.error('加载投资计划失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: string) => {
    try {
      await onDelete(id);
      await loadPlans(); // 重新加载列表
    } catch (error) {
      console.error('删除失败:', error);
    }
  };

  const columns: ColumnsType<SavedStockInvestmentPlan> = [
    {
      title: '证券代码',
      dataIndex: 'stockCode',
      key: 'stockCode',
      width: 100,
      render: (code: string) => <Text strong>{code}</Text>
    },
    {
      title: '证券名称',
      dataIndex: 'stockName',
      key: 'stockName',
      ellipsis: true,
      render: (name: string) => <Text>{name}</Text>
    },
    {
      title: '当前价格',
      dataIndex: 'currentPrice',
      key: 'currentPrice',
      width: 100,
      render: (price: number) => `¥${price.toFixed(2)}`
    },
    {
      title: '投资金额',
      dataIndex: 'totalAmount',
      key: 'totalAmount',
      width: 120,
      render: (amount: number) => `¥${amount.toLocaleString()}`
    },
    {
      title: '买入次数',
      dataIndex: 'buyTimes',
      key: 'buyTimes',
      width: 100,
      align: 'center',
      render: (times: number) => <Tag color="blue">{times}次</Tag>
    },
    {
      title: '投资策略',
      dataIndex: 'strategy',
      key: 'strategy',
      width: 120,
      render: (strategy: string) => {
        const strategyMap: Record<string, { text: string; color: string }> = {
          equal: { text: '等额投资', color: 'green' },
          pyramid: { text: '金字塔', color: 'orange' },
          aggressive: { text: '激进策略', color: 'red' }
        };
        const info = strategyMap[strategy] || { text: strategy, color: 'default' };
        return <Tag color={info.color}>{info.text}</Tag>;
      }
    },
    {
      title: '预期收益',
      key: 'expectedReturn',
      width: 120,
      render: (_, record) => {
        if (record.averagePrice && record.currentPrice) {
          const returnRate = ((record.currentPrice - record.averagePrice) / record.averagePrice * 100);
          return (
            <Text type={returnRate >= 0 ? 'success' : 'danger'}>
              {returnRate >= 0 ? '+' : ''}{returnRate.toFixed(2)}%
            </Text>
          );
        }
        return '-';
      }
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 120,
      render: (date: string) => new Date(date).toLocaleDateString()
    },
    {
      title: '操作',
      key: 'actions',
      width: 240,
      fixed: 'right',
      render: (_, record) => (
        <Space size="small">
          <Button
            type="link"
            size="small"
            icon={<EyeOutlined />}
            onClick={() => onView(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            size="small"
            icon={<EditOutlined />}
            onClick={() => onEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个投资计划吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="link"
              size="small"
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  // 统计信息
  const statistics = {
    totalPlans: plans.length,
    totalInvestment: plans.reduce((sum, plan) => sum + (plan.totalAmount || 0), 0),
    avgInvestment: plans.length > 0 ? plans.reduce((sum, plan) => sum + (plan.totalAmount || 0), 0) / plans.length : 0,
    strategiesCount: {
      equal: plans.filter(p => p.strategy === 'equal').length,
      pyramid: plans.filter(p => p.strategy === 'pyramid').length,
      aggressive: plans.filter(p => p.strategy === 'aggressive').length
    }
  };

  return (
    <div className="stock-investment-plan-list">
      <div style={{ marginBottom: 24 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <Title level={2}>
            <CalculatorOutlined /> 证券投资计划管理
          </Title>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={onCreateNew}
            size="large"
          >
            新增投资计划
          </Button>
        </div>

        {/* 统计概览 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col xs={24} sm={6}>
            <Card size="small">
              <Statistic
                title="投资计划总数"
                value={statistics.totalPlans}
                suffix="个"
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card size="small">
              <Statistic
                title="总投资金额"
                value={statistics.totalInvestment}
                precision={0}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card size="small">
              <Statistic
                title="平均投资金额"
                value={statistics.avgInvestment}
                precision={0}
                prefix="¥"
              />
            </Card>
          </Col>
          <Col xs={24} sm={6}>
            <Card size="small">
              <div>
                <Text type="secondary">策略分布</Text>
                <div style={{ marginTop: 8 }}>
                  <Space size="small" wrap>
                    <Tag color="green">等额 {statistics.strategiesCount.equal}</Tag>
                    <Tag color="orange">金字塔 {statistics.strategiesCount.pyramid}</Tag>
                    <Tag color="red">激进 {statistics.strategiesCount.aggressive}</Tag>
                  </Space>
                </div>
              </div>
            </Card>
          </Col>
        </Row>
      </div>

      {/* 投资计划列表 */}
      <Card>
        {plans.length === 0 && !loading ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={
              <span>
                暂无证券投资计划
                <br />
                <Button type="link" onClick={onCreateNew}>
                  立即创建第一个投资计划
                </Button>
              </span>
            }
          />
        ) : (
          <Table
            columns={columns}
            dataSource={plans}
            rowKey="id"
            loading={loading}
            pagination={{
              total: plans.length,
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              showTotal: (total) => `共 ${total} 条记录`
            }}
            scroll={{ x: 1200 }}
          />
        )}
      </Card>
    </div>
  );
};

export default StockInvestmentPlanList;